package com.ebb;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.kinvey.KCSClient;
import com.kinvey.KinveyUser;
import com.kinvey.util.ScalarCallback;

public class EBBKinveyActivityView extends Activity implements OnClickListener {
    private KCSClient client;
    private TextView viewText;
	private Button btnLogout;
	private String msgResponse;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view);
        
        initLayout();

        Bundle bundle = getIntent().getExtras();
        String objectID = bundle.getString("objectId");

        this.viewText = (TextView) findViewById(R.id.view_text);
        this.client = ((EBBKinveyApplication) getApplication()).getKinveyService();
        
        client.mappeddata("bbs").load(new EBBBBSMapper(), objectID, new ScalarCallback<EBBBBSMapper>() {
            @Override
            public void onSuccess(EBBBBSMapper object) {
                Log.d("onSuccess  >>>>>>>>", object.toString());
                viewText.setText(object.getContent());
            }
            
            @Override
            public void onFailure(Throwable e) {
                super.onFailure(e);
                e.printStackTrace();
            }
        });
    }
    
    private void initLayout() {
		this.btnLogout = (Button) findViewById(R.id.logout_button);
		
		this.btnLogout.setId(0x4001);

		this.btnLogout.setOnClickListener(this);
	}
    
    private void logoutCurrntUser() {
		this.client = ((EBBKinveyApplication) getApplication()).getKinveyService();
		
		KinveyUser currentUser = client.getCurrentUser();
		if(currentUser == null) {
			Log.d("currentUser ::", "currentUser is null");
		} else {
			Log.d("currentUser ::", "currentUser is not null");
			currentUser.logout();
		}
	}
    
    /**
	 * Display a simple alert dialog with the given text and title.
	 * 
	 * @param context
	 *            Android context in which the dialog should be displayed
	 * @param title
	 *            Alert dialog title
	 * @param text
	 *            Alert dialog message
	 */
	protected static void showAlert(Context context, String title, String text) {
		Builder alertBuilder = new Builder(context);
		alertBuilder.setTitle(title);
		alertBuilder.setMessage(text);
		alertBuilder.create().show();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case 0x4001: // Logout
			logoutCurrntUser();
			msgResponse = "Logout";
			Toast.makeText(getBaseContext(), msgResponse, Toast.LENGTH_LONG).show();
			Intent i = new Intent("com.ebb.EBBKinveyActivityMain");
			startActivity(i);
			break;
		}
	}
}
